var express = require('express');
var router = express.Router();
var { sequelize } = require("../config/db");
var user = sequelize.import("../models/user");
var address = sequelize.import("../models/address");
var jwt = require('jsonwebtoken');
var config = require('./../config/config')
var expressJwt = require('express-jwt')
var util = require("./../util/util");
var unless = require('express-unless')


router.use('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {
        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});


router.use(expressJwt({secret: config.jwt_secrets}).unless({
    path: ['/api/user/register/','/api/user/login/','/api/user/detective/']
}));

router.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
        res.status(401).send(util.errorResponse('token验证失败'));
    }
});

var verifyTokenFunction = function(req, res, next){
    var token = req.headers.authorization.split('Bearer ')[1]
    var decoded = jwt.verify(token, config.jwt_secrets,function(err, decoded) {
        if (err) {
            // 返回错误信息
            res.status(401).send(util.errorResponse('token验证失败'));
            return;

        } else {
            req.userId = decoded.id
            return next();
        }
    });
};
verifyTokenFunction.unless = unless

// 自定义 验证策略 中间件
router.use(verifyTokenFunction.unless({
    path: ['/api/user/register/','/api/user/login/','/api/user/detective/']
}));

/* GET home page. */
router.post('/user/register/', function(req, res, next) {
    user.register(req.body.username,req.body.password,(result)=>{
        res.json(result);
    })
});

router.post('/user/login/', function(req, res, next) {
    user.login(req.body.username,req.body.password,(result)=>{
        res.json(result);
    })
});

router.post('/user/userInfo/', function(req, res, next) {
    user.getUserInfo(req.userId,(result)=>{
        res.json(result);
    })
});

router.post('/user/detective/', function(req, res, next) {
    console.log(req.body)
    var token = req.body.token.split('Bearer ')[1]
    jwt.verify(token, config.jwt_secrets,function(err, decoded) {
        if (!err) {
            req.userId = decoded.id
            address.createAddress(req.userId,req.body,(result)=>{
                res.json(result);
            })
        }else {
            res.json(util.errorResponse('用户验证失败'))
        }
    });
});

router.get('/user/detectiveaddresslist/', function(req, res, next) {
    console.log('用户id'+ req.userId)
    console.log('*************')
    address.getAddressList(req.userId,(result)=>{
        res.json(result);
    })
});



module.exports = router;